<?php

namespace app\admin\controller;


use app\admin\service\auth\AdminService;
use app\model\Order;
use app\model\OrderItem;
use app\model\User;
use app\Request;
use think\db\exception\DataNotFoundException;
use think\db\exception\DbException;
use think\db\exception\ModelNotFoundException;
use think\facade\Db;
use think\response\Json;


class IndexController extends AController {

    /**
     * 只需要验证登录，不需要验证权限的请求
     */
//    protected array $middleware = [CheckLogin::class];


    public function init(Request $request, AdminService $adminService): Json
    {

        // 获取最新用户信息
        $admin = $adminService->getLoginInfo();

        // 菜单
        $menus = $adminService->getLoginMenus();

        // 权限
        $rules = $adminService->getLoginRules();

        // 配置信息
//        $system = $this->system;
        // 店铺
//        $shop = $shopService->getInfoById(49);


        $data = [
            'menus' => $menus,
            'admin' => $admin->hidden(['token'])->toArray(),
            'rules' => $rules,
//            'system' => $system,
//            'shop' => $shop
        ];

        return jsonSuccess($data);

    }


    public function statistic(): Json
    {
        // 订单数量
        $todayOrder = Db::table('order')->whereDay('create_time')->count();
        $yesterdayOrder = Db::table('order')->whereDay('create_time', 'yesterday')->count();
        $totalOrder = Db::table('order')->count();
        $orderPer = $yesterdayOrder ? round(($todayOrder-$yesterdayOrder)/$yesterdayOrder, 2) : 0;

        // 销售额（根据订单统计）
        $amountQuery = (new Order())->where('order_status', 'in', ['wait', 'done']);
        $todayAmount = (clone $amountQuery)->whereDay('create_time')->sum('total_amount');
        $yesterdayAmount = (clone $amountQuery)->whereDay('create_time', 'yesterday')->sum('total_amount');
        $totalAmount = (new Order())->sum('total_amount');
        $amountPer = $yesterdayAmount ? round(($todayAmount-$yesterdayAmount)/$yesterdayAmount, 2) : 0;

        // 会员
        $todayUser = Db::table('user')->whereDay('create_time')->count();
        $yesterdayUser = Db::table('user')->whereDay('create_time', 'yesterday')->count();
        $totalUser = Db::table('user')->count();
        $userPer = $yesterdayUser ? round(($todayUser-$yesterdayUser)/$yesterdayUser, 2) : 0;

        // 销量
        $saleQuery = (new OrderItem)->field('id,product_id, SUM(num) as num')->group('product_id')
            ->where('order_status', 'in',['wait', 'done']);
        $totalSales = (clone $saleQuery)->sum("num");
        $todaySales = (clone $saleQuery)->whereDay('create_time')->sum('num');
        $yesterdaySales = (clone $saleQuery)->whereDay('create_time', 'yesterday')->sum("num");
        $salesPer = $yesterdaySales ? round(($todaySales-$yesterdaySales)/$yesterdaySales, 2) : 0;

//        $total = Product::count("id");
//        $todayProduct = Product::whereDay('create_time')->count();
//        $yesterdayProduct = Product::whereDay("create_time", 'yesterday');
//        $productPer = $yesterdayProduct ? round(($todayProduct-$yesterdayProduct)/$yesterdayProduct, 2) : 0;

        return jsonSuccess([
            'todayOrder' => $todayOrder,
            'yesterdayOrder' => $yesterdayOrder,
            'orderPer' => $orderPer,
            'totalOrder' => $totalOrder,
            'todayAmount' => $todayAmount,
            'yesterdayAmount' => $yesterdayAmount,
            'totalAmount' => $totalAmount,
            'amountPer' => $amountPer,
            'todayUser' => $todayUser,
            'yesterdayUser' => $yesterdayUser,
            'totalUser' => $totalUser,
            'userPer' => $userPer,
//            'todayShop' => $todayShop,
//            'yesterdayShop' => $yesterdayShop,
//            'totalShop' => $totalShop,
            'todaySales' => $todaySales,
            'yesterdaySales' => $yesterdaySales,
            'totalSales' => $totalSales,
            'salesPer' => $salesPer
        ]);
    }

    /**
     * 近十五天商品销量柱状图
     * @return Json
     */
    public function salesCharts(): Json
    {
        $days = $this->getDays();

        $sales = [];
        foreach ($days as $day){
            $day = date("Y")."-".$day;
            $sales[] = (new OrderItem)->field("id,SUM(num) as num,product_id")
                ->where('order_status', 'in', ['wait', 'done'])
                ->group("product_id")->whereDay('create_time', $day)->sum("num");
        }
        return jsonSuccess([
            'days' => $days,
            'sales' => $sales
        ]);
    }

    /**
     * 商品销量排行榜
     * @return Json
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    public function salesSort(): Json
    {
        $list = (new OrderItem)->field("id,SUM(num) as num,product_id, product_title")
            ->group("product_id")
            ->order("num desc")
            ->limit(5)
            ->select();
        return jsonSuccess([
            'list' => $list
        ]);
    }

    /***
     * 近十五天销售额
     * @return Json
     */
    public function amountCharts(): Json
    {
        $days = $this->getDays();
        $sales = [];
        foreach ($days as $day){
            $day = date("Y")."-".$day;
            $sales[] = (new Order())
                ->whereDay('create_time', $day)
                ->where('order_status', 'in',['wait', 'done'])
                ->sum("total_amount");
        }
        return jsonSuccess([
            'days' => $days,
            'amounts' => $sales
        ]);
    }

    /** 会员消费金额排行榜
     * @return Json
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    public function userAmountSort(): Json
    {
        $list = (new User())->field("id, nickname as name, total_amount as value")
            ->order("total_amount desc")
            ->limit(20)
            ->select();
        return jsonSuccess([
            'list' => $list
        ]);
    }

    /**
     * 会员佣金排行榜
     * @return Json
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    public function userRewardSort(): Json
    {
        $list = (new User())->field("id, nickname as name, amount as value")
            ->order("amount desc")
            ->limit(20)
            ->select();
        return jsonSuccess([
            'list' => $list
        ]);
    }

    /**
     * 获得最近十五天的日期
     * @return array
     */
    private function getDays(): array
    {
        $days = [];
        for ($i=14; $i>=0; $i--){
            $days[] = date("m-d", strtotime(-$i." day"));
        }
        return $days;
    }


    /**
     * 运费模板
     * @return \think\response\Json
     */
//    public function freightOptions(): \think\response\Json
//    {
//        return jsonSuccess([
//            'freights' => FreightTemplate::miOptions()
//        ]);
//    }


    private function clearDb(){

        $tables = [
            'ad_type',
            'admin_log',
            'kefu_chat_log',
            'kefu_conversation',
            'kefu_user',
            'order',
            'order_item',
            'order_refund',
            'pay_log',
            'product',
            'product_attr',
            'product_attr_value',
            'product_cate',
            'product_reply',
            'shop',
            'shop_address',
            'shop_wx',
            'shopping_car',
            'sys_notice_shop',
            'sys_notice_user',
            'user',
            'user_oauth',
            'user_points_log',
        ];

        foreach ($tables as $v){
            Db::execute("TRUNCATE TABLE ".$v);
        }

    }





}
